package com.example.guardian.client.task;

import com.example.guardian.client.manager.TransactionMessageManager;
import com.example.guardian.client.message.MessageStatus;
import com.example.guardian.client.message.model.MessageModel;
import com.example.guardian.client.proxy.InvokerHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 事务发起者回调定时任务
 *
 * @author gang.wang 2021/12/9
 */
@Component
@EnableScheduling
public class TransactionProviderCallBackTask {

    @Autowired
    private TransactionMessageManager transactionMessageManager;

    @Scheduled(cron = "0/50 * * * * ?")
    public void transactionCallback(){

        List<MessageModel> messageModels = transactionMessageManager.listMessageCallback();
        if (CollectionUtils.isEmpty(messageModels)) {
            return;
        }
        for (MessageModel messageModel : messageModels) {
            Boolean result =  (Boolean) InvokerHolder.get().invokeByGroup(messageModel.getMessageId(), messageModel.getSourceApp());
            if (result){
                messageModel.setStatus(MessageStatus.CONFIRM.name());
            }else {
                messageModel.setStatus(MessageStatus.FAIL.name());
            }
            transactionMessageManager.update(messageModel);
        }
    }
}
